<template>
  <div id="market">
    <EntrustConfirmDrawer ref="confirmDrawer" />
    <div class="title">二币杠杆 USD</div>
    <el-form ref="form" :model="form">
      <el-row :gutter="8">
        <el-col :xs="24">
          <div class="data-panel">
            <div>
              <span class="label">当前价&nbsp;&nbsp;&nbsp;</span
              ><span class="index-price" :style="{ color: price_color }">
                {{ btc_info.indexPrice
                }}<i
                  :style="{ color: price_color, 'font-size': '1.2rem' }"
                  :class="priceIconClass"
              /></span>
            </div>
            <div>
              <span class="label" style="font-weight: 600">
                可用 {{ assert }}
              </span>
              <!-- <span class="label">已锁定 {{ lockedAssert }} </span>
              <span class="label">总共 {{ assert }} </span> -->
            </div>
          </div>
        </el-col>
        <el-col :xs="12"
          ><el-button
            style="width: 100%"
            :type="isOpen ? 'primary' : ''"
            @click="isOpen = true"
            >开仓</el-button
          ></el-col
        >
        <el-col :xs="12"
          ><el-button
            style="width: 100%"
            :type="!isOpen ? 'primary' : ''"
            @click="isOpen = false"
          >
            平仓</el-button
          ></el-col
        >
        <el-col :xs="24">
          <el-form-item prop="region">
            <el-select v-model="form.entrustType" placeholder="委托方式">
              <el-option
                :label="entrustTypes.INDEX_PRICE_ENTRUST.title"
                :value="entrustTypes.INDEX_PRICE_ENTRUST.val"
              ></el-option>
            </el-select>
            <el-popover
              placement="bottom"
              :title="entrustTypeInfo.title"
              width="200"
              trigger="click"
              :content="entrustTypeInfo.info"
            >
              <el-button type="text" slot="reference"
                ><i
                  class="el-icon-question"
                  style="font-size: 1.5rem; margin-left: 16px; color: #c0c4cc"
              /></el-button>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :xs="16">
          <el-form-item>
            <el-input v-model="price" placeholder="价格" :disabled="isCurPrice"
              ><span slot="suffix" style="font-weight: 500">USD</span></el-input
            >
          </el-form-item>
        </el-col>
        <el-col :xs="8">
          <el-button
            :type="isCurPrice ? 'primary' : ''"
            @click="isCurPrice = !isCurPrice"
            >当前价</el-button
          >
        </el-col>
        <el-col :xs="24">
          <el-form-item style="margin-bottom: 2px">
            <template v-if="isOpen">
              <el-input v-model="form.btcCount" placeholder="数量">
                <span slot="suffix" style="font-weight: 500">{{
                  coinName
                }}</span>
              </el-input>
            </template>
            <template v-else>
              <el-input v-model="rateStr" placeholder="数量">
                <span slot="suffix" style="font-weight: 500">{{
                  coinName
                }}</span>
              </el-input>
            </template>
          </el-form-item>
        </el-col>
        <el-col :xs="24" style="margin-bottom: 16px">
          <el-slider
            v-model="rate"
            :marks="amountMarks"
            :format-tooltip="(val) => val + '%'"
            :step="10"
            :show-stops="true"
            @input="setBtcCountByAmountRate"
          >
          </el-slider>
        </el-col>

        <template v-if="isOpen">
          <el-col :xs="24" style="">
            <el-form-item label="杠杆倍数">
              <el-select
                v-model="form.lever"
                size="small"
                @change="setBtcCountByAmountRate(amountRate)"
              >
                <el-option label="x10" :value="10"></el-option>
                <el-option label="x50" :value="50"></el-option>
                <el-option label="x100" :value="100"></el-option>
                <el-option label="x1000" :value="1000"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" style="margin-top: 5px">
            <el-button
              type="success"
              style="width: 100%"
              @click="openPosition(false)"
              >买入开多</el-button
            >
          </el-col>
          <el-col :span="24">
            <div class="label">
              最多可开多:
              {{ (calcMostOpenableBtc(form.lever) || "--") + " " + coinName }}
            </div>
          </el-col>

          <el-col :xs="24" style="margin-top: 5px">
            <el-button
              type="danger"
              style="width: 100%"
              @click="openPosition(true)"
              >卖出开空</el-button
            >
          </el-col>
          <el-col :span="24">
            <div class="label">
              最多可开空:
              {{
                (calcMostOpenableBtc(form.lever, true) || "--") + " " + coinName
              }}
            </div>
          </el-col>
        </template>
        <template v-else>
          <el-col :xs="24" style="margin-top: 5px">
            <el-button
              type="success"
              style="width: 100%"
              @click="closePosition(true)"
              >买入平空</el-button
            >
          </el-col>
          <el-col :span="24">
            <div class="label">
              最多可平:
              {{ (getMostCloseAbleBtc(true) || "--") + " " + coinName }}
            </div>
          </el-col>

          <el-col :xs="24" style="margin-top: 5px">
            <el-button
              type="danger"
              style="width: 100%"
              @click="closePosition(false)"
              >卖出平多</el-button
            >
          </el-col>
          <el-col :span="24">
            <div class="label">
              最多可平:
              {{ (getMostCloseAbleBtc(false) || "--") + " " + coinName }}
            </div>
          </el-col>
        </template>
      </el-row>
      <el-divider />
      <el-tabs v-model="activeTabName">
        <el-tab-pane
          :label="
            '当前委托' + (entrusts.length <= 0 ? '' : `(${entrusts.length})`)
          "
          name="entrust"
        >
          <el-row :gutter="0">
            <el-col
              :span="24"
              v-for="entrust in entrusts"
              v-bind:key="entrust.id"
              ><Entrust :entrust="entrust"
            /></el-col>
          </el-row>
          <el-empty
            v-if="entrusts.length <= 0"
            description="暂无内容"
          ></el-empty>
        </el-tab-pane>
        <el-tab-pane
          :label="
            '仓位' + (positions.length <= 0 ? '' : `(${positions.length})`)
          "
          name="store"
        >
          <el-row :gutter="0">
            <el-col
              :span="24"
              v-for="position in positions"
              v-bind:key="position.id"
              ><Position :position="position"
            /></el-col>
          </el-row>
          <el-empty
            v-if="positions.length <= 0"
            description="暂无内容"
          ></el-empty>
        </el-tab-pane>
        <el-tab-pane
          :label="
            '历史' +
            (historyEntrusts.length <= 0 ? '' : `(${historyEntrusts.length})`)
          "
          name="history"
        >
          <el-row :gutter="0">
            <el-col
              :span="24"
              v-for="entrust in historyEntrusts"
              v-bind:key="entrust.id"
              ><Entrust :entrust="entrust"
            /></el-col>
          </el-row>
          <el-empty
            v-if="historyEntrusts.length <= 0"
            description="暂无内容"
          ></el-empty>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>

<script>
import {
  channels,
  getBtcInfo,
  getUser,
  openEntrust,
  getMostOpenableBtc,
} from "@/js/core";
import { keepTwoDecimal } from "@/js/calcUtils";
import { Message } from "element-ui";
import { EntrustType } from "@/js/constants";

import Entrust from "@/components/Entrust";
import EntrustConfirmDrawer from "@/components/EntrustConfirmDrawer";
import Position from "../components/Position.vue";
export default {
  name: "Market",
  components: { Entrust, Position, EntrustConfirmDrawer },
  data() {
    return {
      entrustTypes: EntrustType,
      coinName: "2B",
      isOpen: true,
      activeTabName: "entrust",
      showConfirm: true,
      form: {
        lever: 10,
        entrustType: EntrustType.INDEX_PRICE_ENTRUST.val,
        price: null,
        btcCount: null,
      },
      amountRate: 0,
      amountMarks: {
        0: "0%",
        100: "100%",
      },
      unsubKey: null,
      price_color: "#303133",
      btc_info: getBtcInfo(),
      priceIconClass: {
        "el-icon-top": false,
        "el-icon-bottom": false,
        "el-icon-minus": true,
      },
      assert: null,
      userPositions: [],
      userEntrusts: [],
      lockedAssert: 0.0,
      isCurPrice: false,
    };
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    setBtcCountByAmountRate(rate) {
      this.form.btcCount =
        keepTwoDecimal(
          (rate / 100) *
            this.calcMostOpenableBtc(this.form.lever, this.form.isShort)
        ) || null;
    },
    updateUserInfo() {
      let u = getUser();
      this.assert = keepTwoDecimal(u.usdTradingAssert);
      this.userPositions = this.userEntrusts = [];
      this.userPositions = u.positions;
      this.userEntrusts = u.entrusts;
      this.setBtcCountByAmountRate(this.amountRate);
    },
    updatePrice(news, old) {
      if (news.indexPrice > old.indexPrice) {
        this.price_color = "#67C23A";
        this.priceIconClass = { "el-icon-top": true };
      } else if (news.indexPrice < old.indexPrice) {
        this.price_color = "#F56C6C";
        this.priceIconClass = { "el-icon-bottom": true };
      } else {
        this.price_color = "#303133";
        this.priceIconClass = { "el-icon-minus": true };
      }
      this.btc_info = news;
      if (
        document.querySelector("#market .data-panel").getBoundingClientRect()
          .y <= 25
      ) {
        // 当价钱不可见时, 显示到.aside-header
        this.showHeaderPrice();
      } else {
        this.closeHeaderPrice();
      }
      this.updateUserInfo();
    },
    calcMostOpenableBtc(lever, isShort) {
      let price = this.form.price;
      if (this.isCurPrice) {
        price = this.btc_info.indexPrice;
      }
      return keepTwoDecimal(getMostOpenableBtc(lever, price, isShort));
    },
    getMostCloseAbleBtc(isShort) {
      let p = getUser().getPosition(isShort);
      if (p != null) {
        return keepTwoDecimal(p.btcCount);
      }
      return null;
    },
    showHeaderPrice() {
      this.$nextTick(() => {
        let node = document
          .querySelector("#market .index-price")
          .cloneNode(true);
        this.closeHeaderPrice();
        document.querySelector(".aside-header").appendChild(node);
      });
    },
    closeHeaderPrice() {
      let node = document.querySelector(".aside-header .index-price");
      if (node != null) {
        node.remove();
      }
    },
    closePosition(isShort) {
      let t = this.form;
      openEntrust({
        type: t.entrustType,
        btcCount: (this.rate * getUser().getPosition(isShort).btcCount) / 100,
        indexPrice: this.price,
        isShort,
        isOpen: false,
        successCallback: (msg) => {
          this.updateUserInfo();
          console.log(msg);
        },
        errCallback: (msg) => {
          Message.error(msg);
          throw new Error(msg);
        },
      });
    },
    openPosition(isShort) {
      let t = this.form;
      openEntrust({
        type: t.entrustType,
        lever: t.lever,
        btcCount: t.btcCount,
        indexPrice: this.price,
        isShort,
        successCallback: (msg) => {
          this.updateUserInfo();
          console.log(msg);
        },
        errCallback: (msg) => {
          Message.error(msg);
          throw new Error(msg);
        },
      });

      //   this.$refs.confirmDrawer.confirm({
      //     entrust: {
      //       type: t.entrustType,
      //       lever: t.lever,
      //       btcCount: t.btcCount,
      //       indexPrice: t.price,
      //       isShort: false,
      //     },
      //     yes: () => {
      //       openPositionForLong({
      //         type: t.entrustType,
      //         lever: t.lever,
      //         btcCount: t.btcCount,
      //         indexPrice: t.price,
      //         isShort: false,
      //         successCallback: (msg) => {
      //           console.log(msg);
      //         },
      //         errCallback: (msg) => {
      //           alert("委托失败: " + msg);
      //         },
      //       });
      //     },
      //   });
    },
  },
  computed: {
    entrustTypeInfo() {
      for (const k in this.entrustTypes) {
        if (this.form.entrustType == this.entrustTypes[k].val) {
          return {
            title: this.entrustTypes[k].title,
            info: this.entrustTypes[k].info,
          };
        }
      }
      return { title: "--", info: "--" };
    },
    price: {
      set: function (p) {
        this.form.price = p;
      },
      get: function () {
        return this.isCurPrice ? this.btc_info.indexPrice : this.form.price;
      },
    },
    positions() {
      return this.userPositions
        .filter(() => true)
        .sort((a, b) => b.timestamp - a.timestamp);
    },
    entrusts() {
      return this.userEntrusts
        .filter((e) => !e.isCompleted & !e.isCancel)
        .sort((a, b) => b.timestamp - a.timestamp);
    },
    historyEntrusts() {
      return this.userEntrusts
        .filter((e) => e.isCompleted || e.isCancel)
        .sort((a, b) => b.timestamp - a.timestamp);
    },
    rate: {
      set: function (rate) {
        this.setBtcCountByAmountRate(rate);
        this.amountRate = rate;
      },
      get: function () {
        return this.amountRate;
      },
    },
    rateStr() {
      return this.rate + "%";
    },
  },
  mounted() {
    this.unsubKey = channels.BTC_INFO.sub(this.updatePrice);
    this.updateUserInfo();
  },
  beforeDestroy() {
    channels.BTC_INFO.unsub(this.unsubKey);
    this.closeHeaderPrice();
  },
};
</script>

<style>
#market {
  text-align: left;
}

#market > .title {
  color: #909399;
}

#market .data-panel {
  padding: 0.5rem;
  color: black;
  font-weight: bolder;
  font-size: 1.8rem;
}

#market .data-panel .label {
  color: #606266;
  font-weight: bolder;
  font-size: 0.8rem;
}

#market .label {
  color: #909399;
  font-size: 0.8rem;
}
</style>
